package com.cameron.vod.controller;


import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cameron.utils.Result;
import com.cameron.vod.service.VodService;
import com.cameron.vod.utils.InitVodClient;
import io.swagger.annotations.ApiModel;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

import java.util.concurrent.TimeUnit;

import static com.cameron.constant.CourseConstant.PLAY_AUTH_CACHE_KEY;
import static com.cameron.vod.utils.OssConstants.*;

/**
 * 视频上传
 *
 * @author Cameron
 */
@ApiModel("视频上传")
@RestController
@RequestMapping("/video-service/vod")
@CrossOrigin
public class VodController {

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    @Resource
    private VodService vodService;

    @PostMapping("upload")
    public Result upload(MultipartFile file) {
        String videoId = vodService.uploadVideo(file);
        return Result.ok().data("videoId", videoId);
    }

    @DeleteMapping("del/{videoId}")
    public Result deleteVideo(@PathVariable String videoId) {
        return vodService.delVideo(videoId) ? Result.ok() : Result.error();
    }

    @GetMapping("getPlayAuth/{id}")
    public Result getPlayAuth(@PathVariable String id) {
        String cacheKey = PLAY_AUTH_CACHE_KEY + id;
        String playAuth = redisTemplate.opsForValue().get(cacheKey);
        if (StringUtils.isNotEmpty(playAuth)) {
            return Result.ok().data("playAuth", playAuth).message("获取凭证成功！");
        }
        try {
            //初始化
            DefaultAcsClient client = InitVodClient.initVodClient(KEY_ID, KEY_SECRET);
            //请求
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            request.setVideoId(id);
            //响应
            GetVideoPlayAuthResponse response = client.getAcsResponse(request);
            //获取播放凭证
            playAuth = response.getPlayAuth();
            if (StringUtils.isNotEmpty(playAuth)) {
                redisTemplate.opsForValue().set(cacheKey, playAuth,1, TimeUnit.MINUTES);
                return Result.ok().data("playAuth", playAuth).message("获取凭证成功！");
            }
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return Result.error().message("获取凭证失败！");
    }
}
